package com.zbc.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zbc.annotations.AuthCheck;
import com.zbc.constants.UserConstant;
import com.zbc.domain.common.DeleteRequest;
import com.zbc.domain.common.Result;
import com.zbc.domain.entity.User;
import com.zbc.domain.request.user.*;
import com.zbc.domain.vo.LoginUserVO;
import com.zbc.domain.vo.UserVO;
import com.zbc.enums.ErrorCode;
import com.zbc.exception.BusinessException;
import com.zbc.service.UserService;
import com.zbc.utils.ThrowUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author fangyu
 * @version v1.0.0
 * @since 2025/9/2 00:28
 */
@Api(tags = "用户模块")
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {
    private final UserService userService;

    /**
     * 用户注册
     *
     * @param request userAccount, userPassword, checkPassword
     * @return 注册成功的用户 id
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public Result<Long> userRegister(@RequestBody UserRegisterRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        String userAccount = request.getUserAccount();
        String userPassword = request.getUserPassword();
        String checkPassword = request.getCheckPassword();
        Long userId = userService.userRegister(userAccount, userPassword, checkPassword);
        return Result.success(userId);
    }

    /**
     * 用户登录
     *
     * @param loginRequest userAccount, userPassword
     * @param request      记录用户登录信息到 session
     * @return 登录用户信息(脱敏)
     */
    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public Result<LoginUserVO> userLogin(@RequestBody UserLoginRequest loginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(loginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = loginRequest.getUserAccount();
        String userPassword = loginRequest.getUserPassword();
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, request);
        return Result.success(loginUserVO);
    }

    /**
     * 获取当前登录用户
     *
     * @param request 用户登录态
     * @return 登录用户信息(脱敏)
     */
    @ApiOperation(value = "获取当前登录用户")
    @GetMapping("/get/login")
    public Result<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        LoginUserVO loginUserVO = userService.getLoginUserVO(loginUser);
        return Result.success(loginUserVO);
    }

    /**
     * 用户注销
     *
     * @param request 用户登录态
     * @return 是否注销成功
     */
    @ApiOperation(value = "用户注销")
    @PostMapping("/logout")
    public Result<Boolean> userLogout(HttpServletRequest request) {
        boolean succeed = userService.userLogout(request);
        return Result.success(succeed);
    }

    /**
     * 创建用户(admin)
     *
     * @param addRequest 创建参数
     * @return 新增用户 id
     */
    @ApiOperation(value = "创建用户(admin)")
    @PostMapping("/add")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Long> addUser(@RequestBody UserAddRequest addRequest) {
        ThrowUtils.throwIf(addRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtil.copyProperties(addRequest, user);
        // 默认密码
        final String password = "12345678";
        String encryptPassword = userService.encryptPassword(password);
        user.setUserPassword(encryptPassword);
        boolean saved = userService.save(user);
        ThrowUtils.throwIf(!saved, ErrorCode.OPERATION_ERROR, "保存用户失败");
        return Result.success(user.getId());
    }

    /**
     * 删除用户(admin)
     *
     * @param deleteRequest id
     * @return 是否删除成功
     */
    @ApiOperation(value = "删除用户(admin)")
    @PostMapping("/delete")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        boolean removed = userService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!removed, ErrorCode.OPERATION_ERROR, "删除用户失败");
        return Result.success(true);
    }

    /**
     * 更新用户(admin)
     *
     * @param updateRequest 更新参数
     * @return 是否更新成功
     */
    @ApiOperation(value = "更新用户(admin)")
    @PostMapping("/update")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Boolean> updateUser(@RequestBody UserUpdateRequest updateRequest) {
        ThrowUtils.throwIf(updateRequest == null || updateRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtil.copyProperties(updateRequest, user);
        boolean updated = userService.updateById(user);
        ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "更新用户失败");
        return Result.success(true);
    }

    /**
     * 用户修改个人信息
     *
     * @param editRequest 修改参数
     * @return 是否修改成功
     */
    @ApiOperation(value = "编辑用户信息")
    @PostMapping("/edit")
    public Result<Boolean> editUser(@RequestBody UserEditRequest editRequest) {
        ThrowUtils.throwIf(editRequest == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(ObjUtil.isEmpty(editRequest.getUserId()), ErrorCode.PARAMS_ERROR);
        String userPhone = editRequest.getUserPhone();
        if (StrUtil.isNotBlank(userPhone) && userPhone.length() > 11) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号不合法");
        }
        String userProfile = editRequest.getUserProfile();
        if (StrUtil.isNotBlank(userProfile) && userProfile.length() > 512) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "个人简介过长");
        }
        User user = new User();
        BeanUtil.copyProperties(editRequest, user);
        boolean updated = userService.updateById(user);
        ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "修改用户信息失败");
        return Result.success(true);
    }

    /**
     * 根据 id 获取用户(admin)
     *
     * @param id 用户 id
     * @return 用户信息
     */
    @ApiOperation(value = "根据 id 获取用户(admin)")
    @GetMapping("/get")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<User> getUserById(@RequestParam("id") Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isNull(user), ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        return Result.success(user);
    }

    /**
     * 根据 id 获取用户信息(脱敏)
     *
     * @param id 用户 id
     * @return 用户信息(脱敏)
     */
    @ApiOperation(value = "根据 id 获取用户信息脱敏)")
    @GetMapping("/get/vo")
    public Result<UserVO> getUserVOById(@RequestParam("id") Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isNull(user), ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        UserVO userVO = userService.getUserVO(user);
        return Result.success(userVO);
    }

    /**
     * 获取用户列表(admin)
     *
     * @param userQueryRequest 查询参数
     * @return 用户列表
     */
    @ApiOperation(value = "分页获取用户列表(admin)")
    @PostMapping("/list/page/vo")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        int current = userQueryRequest.getCurrent();
        int pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize), userService.getQueryWrapper(userQueryRequest));
        // 设置 UserVO 的当前页码, 每页大小, 总记录数与 User 一致, 但只是空壳子, 里面没数据
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        // 取出分页中的数据并转换为 UserVO
        List<UserVO> userVOPageList = userService.getUserVOList(userPage.getRecords());
        // 设置数据给 UserVO, 这样就有数据了
        userVOPage.setRecords(userVOPageList);
        return Result.success(userVOPage);
    }
}
